package com.test.exception;

import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.PrintWriter;

/**
 * @description:
 * @author: wyp
 * @date: 2024/12/25 9:55
 */
@Component
@Log4j2
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.reset();
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        String message = "";
        Throwable cause = authException.getCause();
        if (cause instanceof InvalidClassException) {
            message = "token无效";
        } else {
            message = "认证失败: " + authException.getMessage();
        }
        log.error("请求发生错误---->异常信息:{}", message);
        throw new RuntimeException("请求发生错误---->异常信息: " + message);
    }

    protected void write(HttpServletResponse response, String str) {
        PrintWriter out = null;
        try {
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.write(str);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
